use std::sync::Arc;
use tonic::{Request, Response, Status};
use tracing::{info, warn};

use crate::proto::{
    nacos_service_server::NacosService,
    ClusterRequest, ClusterResponse,
    DataSyncRequest, DataSyncResponse,
    MemberChangeRequest, MemberChangeResponse,
    HealthCheckRequest, HealthCheckResponse,
};

/// 集群管理trait
#[async_trait::async_trait]
pub trait ClusterService: Send + Sync {
    async fn get_cluster_info(&self) -> Result<String, tonic::Status>;
    async fn add_node_from_info(&self, node_info: String) -> Result<(), tonic::Status>;
    async fn remove_node(&self, node_id: &str) -> Result<(), tonic::Status>;
    async fn is_healthy(&self) -> Result<bool, tonic::Status>;
}

/// 数据同步trait
#[async_trait::async_trait]
pub trait DataSyncService: Send + Sync {
    async fn handle_sync_message(
        &self,
        sync_type: String,
        from_node: String,
        data: String,
        version: u64,
        timestamp: u64,
    ) -> Result<String, tonic::Status>;
}

/// gRPC服务实现
pub struct NacosGrpcService {
    cluster_service: Arc<dyn ClusterService>,
    data_sync_service: Arc<dyn DataSyncService>,
}

impl NacosGrpcService {
    pub fn new(
        cluster_service: Arc<dyn ClusterService>,
        data_sync_service: Arc<dyn DataSyncService>,
    ) -> Self {
        Self {
            cluster_service,
            data_sync_service,
        }
    }
}

#[tonic::async_trait]
impl NacosService for NacosGrpcService {
    /// 处理集群间节点通信
    async fn handle_cluster_request(
        &self,
        request: Request<ClusterRequest>,
    ) -> Result<Response<ClusterResponse>, Status> {
        let req = request.into_inner();
        info!("收到集群请求: type={}, from={}", req.request_type, req.from_node);

        match req.request_type.as_str() {
            "heartbeat" => {
                let response = ClusterResponse {
                    success: true,
                    message: "heartbeat ok".to_string(),
                    data: String::new(),
                };
                Ok(Response::new(response))
            }
            "node_info" => {
                let cluster_info = self.cluster_service.get_cluster_info().await?;
                
                let response = ClusterResponse {
                    success: true,
                    message: "node info".to_string(),
                    data: cluster_info,
                };
                Ok(Response::new(response))
            }
            _ => {
                warn!("未知集群请求类型: {}", req.request_type);
                Err(Status::invalid_argument("未知的请求类型"))
            }
        }
    }

    /// 处理数据同步请求
    async fn handle_data_sync(
        &self,
        request: Request<DataSyncRequest>,
    ) -> Result<Response<DataSyncResponse>, Status> {
        let req = request.into_inner();
        info!("收到数据同步请求: type={}, from={}", req.sync_type, req.from_node);

        let result = self.data_sync_service.handle_sync_message(
            req.sync_type,
            req.from_node,
            req.data,
            req.version,
            req.timestamp,
        ).await?;

        let response = DataSyncResponse {
            success: true,
            message: "sync completed".to_string(),
            data: result,
        };

        Ok(Response::new(response))
    }

    /// 处理集群成员变更
    async fn handle_member_change(
        &self,
        request: Request<MemberChangeRequest>,
    ) -> Result<Response<MemberChangeResponse>, Status> {
        let req = request.into_inner();
        info!("收到成员变更请求: action={}, node={}", req.action, req.node_id);

        match req.action.as_str() {
            "join" => {
                // 处理节点加入
                self.cluster_service.add_node_from_info(req.node_info).await?;
                
                let response = MemberChangeResponse {
                    success: true,
                    message: "节点加入成功".to_string(),
                };
                Ok(Response::new(response))
            }
            "leave" => {
                // 处理节点离开
                self.cluster_service.remove_node(&req.node_id).await?;
                
                let response = MemberChangeResponse {
                    success: true,
                    message: "节点离开成功".to_string(),
                };
                Ok(Response::new(response))
            }
            _ => {
                warn!("未知成员变更操作: {}", req.action);
                Err(Status::invalid_argument("未知的操作类型"))
            }
        }
    }

    /// 处理健康检查
    async fn health_check(
        &self,
        request: Request<HealthCheckRequest>,
    ) -> Result<Response<HealthCheckResponse>, Status> {
        let req = request.into_inner();
        
        let is_healthy = self.cluster_service.is_healthy().await?;

        let response = HealthCheckResponse {
            healthy: is_healthy,
            message: if is_healthy {
                "服务健康".to_string()
            } else {
                "服务异常".to_string()
            },
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs(),
        };

        Ok(Response::new(response))
    }
}